from flask import Flask, jsonify, abort, request
from flask_cors import CORS
import random
import os.path


app = Flask(__name__)
cors = CORS(app)

# .txt .jpg .mp4 .mp3 .png .pdf .bmp
# .doc .docx .xls .xlsx .csv .ppt .pptx


class LicensePlate:
    def __init__(self):
        self.__nums = list(range(0, 10))
        self.__alph = list('ABCDEFGHJKLMNPQRSTUVWXYZ')
        self.__c = 2
        self.__headFile = "./LicenseHead.txt"
        self.__licensedFile = "./Licensed.txt"

    def __str__(self):
        return f"LicensePlate(c = {self.__c})"

    @property
    def c(self):
        return self.__c

    @c.setter
    def c(self, value):
        if value < 0 or value > 5:
            raise Exception("Invalid setting!")
        self.__c = value

    def __getNums(self):
        random.shuffle(self.__nums)
        nums = []

        for x in range(5 - self.__c):
            nums.append(str(self.__nums[x]))

        return nums

    def __getChars(self):
        random.shuffle(self.__alph)
        chars = []

        for x in range(self.__c):
            chars.append(self.__alph[x])

        return chars

    def __getLicenseHead(self, district):
        if not os.path.isfile(self.__headFile):
            raise Exception(f"{self.__headFile} does not exists!")

        lh = ''
        hf = ''

        try:
            # r, read, 读取，只读
            # a, add, 添加，在末尾添加
            # w, write, 写，从文件开头写
            hf = open(self.__headFile, 'r', encoding='utf-8')
            hflst = hf.read().split('\n')
            for item in hflst:
                if item.find(district) >= 0:
                    lh = item.split(' ')[1]
        except Exception as e:
            raise Exception(str(e))
        finally:
            hf.close()
            return lh

    def getLicensePlate(self, district):
        lh = self.__getLicenseHead(district)

        # 云A.AB123
        l = self.__getChars() + self.__getNums()
        random.shuffle(l)
        lstr = ""

        for x in l:
            lstr += x

        return lh + "." + lstr

    def ifExistsLicensePlate(self, licensePlate):
        hf = ''
        flag = False
        try:
            # r, read, 读取，只读
            # a, add, 添加，在末尾添加
            # w, write, 写，从文件开头写
            hf = open(self.__licensedFile, 'r', encoding='utf-8')
            hflst = hf.read().split('\n')
            for item in hflst:
                if item.find(licensePlate) >= 0:
                    flag = True
        except Exception as e:
            raise Exception(str(e))
        finally:
            hf.close()
            return flag

    def writeLicensePlate(self, licensePlate):
        if self.ifExistsLicensePlate(licensePlate):
            return False
        else:
            try:
                # r, read, 读取，只读
                # a, add, 添加，在末尾添加
                # w, write, 写，从文件开头写
                hf = open(self.__licensedFile, 'a', encoding='utf-8')
                hf.write('\n' + licensePlate)
            except Exception as e:
                raise Exception(str(e))
            finally:
                hf.close()

        return True


@app.route("/licenseplate/get/<string:lphead>", methods=['GET'])
def getlp(lphead):
    lpx = LicensePlate()
    rst = lpx.getLicensePlate(lphead)

    return jsonify({"license": rst})


@app.route("/licenseplate/write/<string:lp>", methods=['GET'])
def writelp(lp):
    lpx = LicensePlate()
    rst = lpx.writeLicensePlate(lp)

    return jsonify({"isOK": rst})


@app.route("/licenseplate/exists/<string:lp>", methods=["GET"])
def checkLicensePlate(lp):
    lpx = LicensePlate()
    flag = lpx.ifExistsLicensePlate(lp)

    return jsonify({"isExists": flag})


if __name__ == "__main__":
    app.run()
